// pages/login/login.js
const util = require('../../utils/util.js')

const config = require('../../utils/config.js')

//获取应用实例
const app = getApp()
Page({
  data: {
    data: [],
    meta: {},
    latitude: 25.488999,
    longitude: 118.25191,
    address: '',
    markers: [],
    clickMarkerId:'',
    clickMarkerObj:{},
    status_count: {
      total_count: 2474,
      consumption: "1737.95",
      normal_upload_rate: "10.75%",
    },
    value: "",
    meter_number:'',
    page: 1,
    per_page: 10,
    index: 0,
    typeIndex:0,
    typeObj:[{name:'资产编号',key:'name'},{name:'用户编号',key:'user_number'},{name:'设备编号',key:'number'}],
    typeKey:'name'
  },
  onPickerChange(e) {
    const index = e.detail.value;
    const selectedObject = this.data.typeObj[index];
    this.setData({ typeIndex: index,typeKey:selectedObject.key });
    console.log('选中的对象 key：', selectedObject.key);
    console.log('选中的对象名称：', selectedObject.name);
  },
  onLoad: function (options) {
    console.log('onLoad')
    const that=this
    this.fecth({
      page: 1,

    })
    if(app.globalData.userInfo){
      this.timer=setInterval(function (){
        console.log('setInterval')
        that.fecth({
          page: 1,
        },true)
      },20000)
    }



  },
  bindPickerChange: function (e) {
    const that = this
    console.log('picker发送选择改变，索引值为', e.detail.value)
    console.log(e);
    this.setData({
      index: e.detail.value,
    }, function () {
      this.fecth({
        page: 1,

      })
    })

  },
  bindtapDetail: function (e) {
    wx.navigateTo({
      url: `/pages/list_detail/detail?number=${this.data.clickMarkerObj.number}&id=${this.data.clickMarkerObj.id}`
    })
  },
  bindinput(e) {
    this.setData({
      value: e.detail.value
    })
  },
  bindinputMeterNumber(e) {
    this.setData({
      meter_number: e.detail.value
    })
  },
  bindtap:function (e){
    console.log(e)
  },
  bindmarkertap:function (e){
    console.log(e)
    const that=this
    this.setData({
      clickMarkerId:e.markerId
    },function (){
      wx.request({
        url: `${config.prefix}/hydrants`,
        header: {
          Authorization: `Bearer ${app.globalData.userInfo.token}`
        },
        method: 'GET',
        data: {
          number: that.data.clickMarkerId
        },
        success: function (res) {
          console.log('get res', res)
          setTimeout(function () {
            wx.hideLoading()
          }, 100)
          if (res.statusCode === 200) {
            if( res.data.data.length===1){
              if(res.data.data[0].latest_data.rtu&&res.data.data[0].latest_data.rtu.parameters){
                that.setData({
                  clickMarkerObj:{
                    ...res.data.data[0],
                    renderMeterStatus:(res.data.data[0].latest_data.rtu&&res.data.data[0].latest_data.rtu.parameters)?util.renderMeterStatus(res.data.data[0].latest_data.rtu.parameters.meter_status):[],
                    collected_at:res.data.data[0].latest_data.rtu.collected_at,
                    ...res.data.data[0].latest_data.rtu.parameters,

                  }
                })
              }else{
                that.setData({
                  clickMarkerObj:{
                    ...res.data.data[0],
                  }
                })
              }
            }




          } else {
            util.converErrorCodeToMsg(res)
          }
        }


      })
    })


  },
  fecth: function (params,isSetInterval) {
    wx.stopPullDownRefresh();
    const that = this;
    if(!isSetInterval){
      wx.showLoading({
        title: '加载中...',
        mask: true
      });
    }

    if (!app.globalData.userInfo) {
      wx.reLaunch({
        url: '/pages/login/login'
      })
      return false;
    }
    wx.request({
      url: `${config.prefix}/hydrants`,
      header: {
        Authorization: `Bearer ${app.globalData.userInfo.token}`
      },
      method: 'GET',
      data: {
        per_page: 500,
        [this.data.typeKey]: this.data.value,
        order_direction: 'desc',
        order_column: "number",
        ...params
      },
      success: function (res) {
        console.log('get res', res)
        setTimeout(function () {
          wx.hideLoading()
        }, 100)
        if (res.statusCode === 200) {
          let markers=[]
          for(let i=0;i<res.data.data.length;i++){
            res.data.data[i]={
              ...res.data.data[i],
              renderMeterStatus:(res.data.data[i].latest_data.rtu&&res.data.data[i].latest_data.rtu.parameters)?util.renderMeterStatus(res.data.data[i].latest_data.rtu.parameters.meter_status):[],

            }
            if(res.data.data[i].latest_data.rtu&&res.data.data[i].latest_data.rtu.collected_at){
              res.data.data[i]={
                ...res.data.data[i],
                renderMeterStatus:(res.data.data[i].latest_data.rtu&&res.data.data[i].latest_data.rtu.parameters)?util.renderMeterStatus(res.data.data[i].latest_data.rtu.parameters.meter_status):[],
                collected_at:res.data.data[i].latest_data.rtu.collected_at,
                ...res.data.data[i].latest_data.rtu.parameters
              }
            }
            markers.push({
              id:  Number(res.data.data[i].number),
              latitude:res.data.data[i].latitude,
              longitude:res.data.data[i].longitude,
              iconPath:res.data.data[i].alarm===1?'/images/xfs-red.png':'/images/xfs-blue.png',
              width: '24', // 标记点图标宽度
              height: '24', // 标记点图标高度
              collision:'marker'
            })
          }
          console.log('获取成功');
          if (params.page === 1) {
            that.setData({
              markers:markers,
              data: res.data.data,
              meta: res.data.meta,
              page: params.page,

            })
          } else {

            let pushData = that.data.data.concat(res.data.data)

            that.setData({
              data: pushData,
              meta: res.data.meta,
              page: params.page
            })
          }


        } else {
          util.converErrorCodeToMsg(res)
        }
      }


    })
  },

  handleTapItem: function (e) {
    console.log(e.currentTarget.dataset.item)
    wx.navigateTo({
      url: `/pages/issue_detail/detail?number=${e.currentTarget.dataset.item.number}&id=${e.currentTarget.dataset.item.id}`
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log('onPullDownRefresh')
    this.fecth({
      page: 1,
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('onShow')
    this.fecth({
      page: 1,

    })
    const that=this
    console.log('this.timer',this.timer)
    if(!this.timer){
      if(app.globalData.userInfo){
        this.timer=setInterval(function (){
          console.log('setInterval')
          that.fecth({
            page: 1,
          },true)
        },100000)
      }
    }
  },
  bindtapLocation: function (e) {
    wx.openLocation({
      latitude: Number(this.data.clickMarkerObj.latitude), // 纬度，范围为-90~90，负数表示南纬
      longitude:Number(this.data.clickMarkerObj.longitude), // 经度，范围为-180~180，负数表示西经
      scale: 14, // 缩放比例
    })
  },
  onHide:function (){
      if(this.timer){
        console.log('clearInterval')
        clearInterval(this.timer)
        this.timer=null
      }
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('onPullDownRefresh')
    console.log(this.data)
    if (this.data.page >= this.data.meta.last_page) {
      // wx.showToast({
      //   title: '没有更多数据',
      //   icon: 'none'
      // })
      return false;
    }
    this.fecth({
      page: this.data.page + 1,

    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})